/**
 * Created by SZ on 2018/05/23.
 */
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const moment = require('moment');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;
const jwt_key = "greengis";

//用户表（U表）
const UserSchema = new Schema({
    //用户名
    name: String,
    //密码
    password: String,
    //用户状态:  0 = off 1 = on 2 = lock
    status: Number,
    //用户手机
    mobile: String,
    //邮件
    email: String,
    //头像
    head: String,
    //签名
    sign: String,
    //1 = super admin, 0 = common user
    super: Number,
    //用户介绍
    description: String,
    //轨迹
    location: {
        x: Number,
        y: Number,
        date: Date
    },
    //应删除，用户token，token无需保存，登录以及verify会重新生成并返回，刷新时效
    token: String,
    //随机盐值，暂未启用
    salt: String,
    //token授权
    authority: {
        create_date: Date,  //授权日期
        valid_date: Date,    //有效期
        key: String           //密钥
    }
}, {collection: 'users'});

/**
 * Methods
 */
UserSchema.methods = {
    register: function () {
        this.encrypt(this.password);
        this.token = this.jwt();
    },
    encrypt: function (plain) {
        this.password = bcrypt.hashSync(plain, 10);
        return this.password;
    },
    compare: function (plain) {
        return bcrypt.compareSync(plain, this.password);
    },
    jwt: function () {
        var obj = {
            id: this._id,
            exp: moment().add(2, 'day').unix()
        };
        return jwt.sign(obj, jwt_key);
    },
    auth: function () {
        const obj = {
            id: this._id,
            exp: moment(this.authority.valid_date).unix()
        };
        this.authority.key = jwt.sign(obj, jwt_key);
        this.authority.create_date = new Date();
    }
};

/**
 * Statics
 */
UserSchema.statics = {
    verify: function (token, callback) {
        jwt.verify(token, jwt_key, callback);
    }
};


const User = mongoose.model('User', UserSchema);
module.exports = User;